<template>
  <el-dialog :visible.sync="isShow" width="600px" :show-close="false" class="register">
    <div class="title" slot="title">用户注册</div>
    <!-- 头像上传 -->
    <el-form :model="form" label-width="90px" ref="form" :rules="rules">
      <el-form-item label="头像" class="upload-img" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="baseURL+'/uploads'"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.avatar" :src="baseURL+'/'+form.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <!-- 表单验证注册内容 -->
      <!-- 昵称 -->
      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <!-- 邮箱 -->
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <!-- 手机 -->
      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <!-- 图形码 -->
      <el-form-item label="图形码" prop="code">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.code"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <img @click="goCode" class="code_img" :src="baseURL+codeUrl" alt />
          </el-col>
        </el-row>
      </el-form-item>

      <!-- 验证码 -->
      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <!-- 倒计时 -->
            <el-button @click="getPhone" :disabled="totalTime!=5">
              获取用户验证码
              <span v-if="totalTime!=5">({{totalTime}})</span>
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>

    <div slot="footer" class="footer">
      <el-button @click="isShow = false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getPhoneCode, goRegister } from "@/api/register.js";
export default {
  watch: {
    isShow(newVal) {
      if (newVal == false) {
        // 清空表单
        this.$refs.form.resetFields();
      }
    },
  },
  data() {
    return {
      form: {
        avatar: "",
        username: "",
        email: "",
        phone: "",
        password: "",
        code: "",
        rcode: "",
      },
      totalTime: 5,
      isShow: false,
      baseURL: process.env.VUE_APP_URL,
      // imageUrl: "",
      codeUrl: "/captcha?type=sendsms",
      rules: {
        avatar: [
          {
            required: true,
            message: "请上传头像",
            trigger: "change",
          },
          {},
        ],
        username: [
          {
            required: true,
            message: "请输入昵称",
            trigger: "change",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "change",
          },

          {
            validator: (rule, value, callback) => {
              let _fe = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (_fe.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的邮箱地址"));
              }
            },
            trigger: "change",
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "change",
          },
          {
            validator: (rule, value, callback) => {
              let _fe = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (_fe.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的手机号"));
              }
            },
            trigger: "change",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "change",
          },
        ],
        code: [
          {
            required: true,
            message: "请输入图形码",
            trigger: "change",
          },
        ],
        rcode: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    handleAvatarSuccess(res) {
      // console.log(res);
      // this.imageUrl = res.data.file_path;
      this.form.avatar = res.data.file_path;
      this.$refs.form.validateField(["avatar"]);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    submit() {
      this.$refs.form.validate((result) => {
        if (result) {
          goRegister(this.form).then((res) => {
            console.log(res);
            this.isShow = false;
            this.$message.success("注册成功");
          });
        } else {
          this.$message.error("登录失败");
        }
      });
    },
    goCode() {
      this.codeUrl = "/captcha?type=sendsms&fdsf=" + Date.now();
    },

    getPhone() {
      let _num = 0;
      // 获取验证  需要同时手机号和图形码验证成功,需要调用el-form里面的validateField方法
      this.$refs.form.validateField(["phone", "code"], (errorMessage) => {
        // console.log(errorMessage);
        if (errorMessage == "") {
          _num++;
        }
      });
      // console.log(_num);
      if (_num == 2) {
        // this.$message.success("验证通过");
        // 倒计时
        // 一开始就减一
        this.totalTime--;
        // 计时器
        let _interval = setInterval(() => {
          // 让总时间减减
          this.totalTime--;
          // 如果减到0 就还原
          if (this.totalTime == 0) {
            this.totalTime = 5;
            // 清理计时器
            clearInterval(_interval);
          }
        }, 1000);

        // this.$axios({
        //   url: "/sendsms",
        //   method: "post",
        //   data: {
        //     code: this.form.code,
        //     phone: this.form.phone,
        //   },
        // })
        getPhoneCode({
          code: this.form.code,
          phone: this.form.phone,
        }).then((res) => {
          this.$message.success(res.data.data.captcha + "");
        });
      } else {
        this.$message.error("验证失败");
      }
    },
  },
};
</script>

<style lang="less">
.register {
  .title {
    background: linear-gradient(to right, #01c6fa, #1493fa);
    height: 53px;
    line-height: 53px;
    font-size: 14px;
    font-family: Microsoft YaHei Regular, Microsoft YaHei Regular-Regular;
    font-weight: 400;
    text-align: center;
    color: #ffff;
  }
  .el-dialog__header {
    padding: 0;
  }
  .footer {
    display: flex;
    justify-content: center;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .upload-img {
    text-align: center;
  }
  .code_img {
    line-height: 40px;
    width: 100%;
  }
}
</style>
